package com.karst87.sqlite.study
{
	import flash.data.SQLConnection;
	import flash.events.EventDispatcher;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;

	internal class DataBaseDealer extends EventDispatcher
	{
		private var dbFile : File = null ;
		private var sqlConn : SQLConnection = null ;
		
		public function DataBaseDealer()
		{
			createDBFile() ;
		}
		
		public function getSqlConn() : SQLConnection 
		{
			return sqlConn ;
		}

		private function createDBFile() : void
		{
			if( dbFile == null ) 
			{
				/**
				 * 在系统存储位置创建
				 * 如：C:\Documents and Settings\...\Application Data\SQLiteStudy\Local Store
				 dbFile = File.applicationStorageDirectory.resolvePath( "sqlite.db" ) ;
				 */
				dbFile = File.applicationDirectory.resolvePath( "sqlite.db" ) ;
			}
		}

		public function createSqlConn() : void
		{
			if( sqlConn == null ) 
			{
				sqlConn = new SQLConnection() ;
			}
			sqlConn.addEventListener( SQLEvent.OPEN, openHandler ) ;
			sqlConn.addEventListener( SQLErrorEvent.ERROR, errorHandler ) ;
			sqlConn.openAsync( dbFile ) ;
		}
		
		private function openHandler( $event : SQLEvent ) : void
		{
			trace( "Complete Successfully" ) ;
			dispatchEvent( $event ) ;
		}
		
		private function errorHandler( $event : SQLErrorEvent ) : void
		{
			trace( "Error" ) ;
			trace( "Error Message: " + $event.error.message ) ;
			trace( "Error Details: " + $event.error.details ) ;
		}
	}
}